<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Exception;
use think\Validate;
use think\Cache;
use think\Session;
use think\Request;
use lib\Rest;

class Web extends Controller
{
    public $accountSid= '8a216da860bad76d0160e40720ff1176';
    //说明：主账号，登陆云通讯网站后，可在控制台首页看到开发者主账号ACCOUNT SID。

    public $accountToken= '11f1d38cbf314b4b96c21b8593788b5f';
    //说明：主账号Token，登陆云通讯网站后，可在控制台首页看到开发者主账号AUTH TOKEN。

    public $appId= '8a216da860bad76d0160e4072158117d';
    //说明：请使用管理控制台中已创建应用的APPID。

    public $serverIP='app.cloopen.com';
    //说明：生产环境请求地址：app.cloopen.com。


    public $serverPort='8883';
    //说明：请求端口 ，无论生产环境还是沙盒环境都为8883.

    public $softVersion='2013-12-26';
    //说明：REST API版本号保持不变。



    /**
     * 显示首页
     *
     * @return \think\Response
     */
    public function index()
    {
        if( Request::instance()->isMobile()){
        $this->redirect('/m');
       }

        //判断cookie
        // 判断是否免登录
        if(cookie('tel')){
            // 查询数据 直接登录
            $data = Db::name('web_users')
                ->field('nickname, id')
                ->where('tel', cookie('tel'))
                ->find();

            // 存session
            session('web', ['nickname' => $data['nickname'] , 'uid' => $data['id']]);
        }

        //显示所有的课程大分类
        $list = Db::name('category')->where('pid','0')->where('display','1')->limit(10)->select();
        // dump($list);die;

        // dump($list);die;
       $discus = Db::name('together_discus')->field('discontent')->limit('6')->select();
       // dump($discus);die;
       $hot = Db::name('course')->alias('c')
            ->field('c.name,c.id,c.description,p.address')
            ->join('coursepicture p','p.courseid=c.id')
            ->where('c.hot','1')
            ->where('c.display','1')
            ->where('p.cover','1')
            ->limit(3)
            ->select();
            // dump($hot);die;
       // 商品列表分类/商品排列
       foreach($list as $k => $v){
//            dump($v['id']);
            $list[$k]['goods'] = $this->find_cate($v['id'],4);
            // dump($list[$k]);
       }
            // dump($list);die;
            
        return view('home',[
                    'list'=>$list,
                    'discus'=>$discus,
                    'hot'=>$hot
                ]);
    }

    

    /**
     * 前台登陆页
     * 
     */
    public function login ()
    {
        return view('web/logining');
    }

    /**
     * 前台登入
     *
     * @return \think\response\View
     */
    public function doLogin ()
    {
        // 接收数据
        $data = input('post.');
        $tel = $data['tel'];
       

        //验证数据
        $validate = new Validate(
            [
                'tel' => "require",
                'pass' => 'require|max:16',
            ],
            [
                'tel.require' => '手机号码不能为空,请重试...',
                // 'tel.regex' => '手机号码必须符合规范,请重试...',
                'pass.require' => '密码不能为空,请重试...',
                'pass.max' => '密码最多只能16位,请重试...',
            ]);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        //        var_dump($data); die;

        /*// 验证验证码是否正确
        $code = $data['code'];
        if( !($code == 888888)){
            $this->error('验证码错误!');
        }*/

        // 验证账号是否存在
        $res1 = Db::name('web_users')
            ->field('id, nickname, status')
            ->where('tel', $tel)
            ->find();
        $uid = $res1['id'];
        $nickname = $res1['nickname'];

        if ($res1['id'] == 0) {
            $this->error('用户不存在有误,请重试...');
        }

        // 验证是否被限制
        if($res1['status'] == 2){
            $this->error('您的账号已被禁用,请联系管理员解封...');
        }


        // 验证密码
        $pass = sha1($data['pass']);

        $res2 = Db::name('web_users')
            ->field('id,face')
            ->where('tel', $tel)
            ->where('pass', $pass)
            ->find();


        if ($res2) {

            // 登入成功 删除cache
            Cache::rm("web");

            // 判断是否免登录
            if( !empty($data['rem']) ){
                cookie('tel', $tel, 604800);
            }

            $face = empty($res2['face'])?'20180426/577e896812970c6c85623de5999fa121.jpg':$res2['face'];

            session('web', ['uid' => $uid, 'tel' => $tel, 'nickname' => $nickname,'face'=>$face]);

//            var_dump(session('web')['nickname']);die;


            $this->redirect('/');
        } else {



            // 用户密码错误 记录错误次数
            $this->countnum();

        }

    }

    public function countnum ()
    {
        if( isset(Cache::get('web')['time']) ){

            if( Cache::get('web')['time'] < 2 ){
                $nums = Cache::get('web')['time'];
                Cache::set('web', ['time'=> $nums+1] );
                $this->error('用户名或密码有误,请重试...');
            } else {
                Cache::set('web', ['time' => 4], 10);
                $this->error('已达到登入次数限制, 请稍后再试...');
            }

        } else {
            Cache::set('web', ['time' => 1]);
            $this->error('用户名或密码有误,请重试...');
        }
    }


    /**
     * 前台注册页
     */
    public function register ()
    {
        return view('register');
    }

    public function doRegister ()
    {
        $data = input('post.');

        $tel = $data['tel'];
        $tel == session('tel')? '':$this->error('手机号不一致,请重试...');

        $code = $data['code'];
        $code == session('smscode')?'': $this->error('验证码有误,请重试...');
    //         dump($data); dump('aa'.session('smscode'));die;

        //验证数据
        $validate = new Validate(
            [
                'tel' => "require",
                'pass' => 'require|max:16',
                'repass' => 'max:16|confirm:pass',
            ],
            [
                'tel.require' => '手机号码不能为空,请重试...',
                // 'tel.regex' => '手机号码必须符合规范,请重试...',
                'pass.require' => '密码不能为空,请重试...',
                'pass.max' => '密码最多只能16位,请重试...',
                'repass.require' => '密码不能为空,请重试...',
                'repass.confirm' => '两次密码不一致,请重试...',

            ]);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        //        var_dump($data); die;

        // 验证账号是否存在
        $res = Db::name('web_users')
            ->field('id')
            ->where('tel', $tel)
            ->find();

        if ($res) {
            $this->error('用户已存在,请重试...');
        }
        // 删除repass
        unset($data['repass']);
        unset($data['code']);

        $data['pass'] = sha1($data['pass']);
        $data['nickname'] = '新同学'.$tel;

        // 添加用户
        // 开启事务
        $success = null;
        Db::startTrans();

        try{
            $add = Db::name('web_users')
                ->insert($data);

            if($add){
                Db::commit();
                $this->success('注册成功, 请登录!', '/webLogin');
            }

        }catch(Exception $exception){
            Db::rollback();
            $this->error('由于未知错误,添加失败,请重试...');
        }
    }

    public function sendCode ($tel)
    {
        // 随机生成验证码
        $num = rand(100000, 999999);
        session('smscode',$num,'think');
        session('tel',$tel,'think');
        return $this->sendTemplateSMS($tel,array($num,'10') ,'1',$num);

    }

    public function sendTemplateSMS($to,$datas,$tempId,$num)
    {
        // 初始化REST SDK
        //        global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;
        $rest = new REST($this->serverIP,$this->serverPort,$this->softVersion);
        $rest->setAccount($this->accountSid,$this->accountToken);
        $rest->setAppId($this->appId);


        // 发送模板短信
        /*echo "Sending TemplateSMS to $to ";*/
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        if($result == NULL ) {
            echo "result error!";
        }
        if($result->statusCode!=0) {
            echo "模板短信发送失败!";
            echo "error code :" . $result->statusCode . "";
            echo "error msg :" . $result->statusMsg . "";
            //下面可以自己添加错误处理逻辑
        }else{
            /*echo "模板短信发送成功!";
            // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            echo "dateCreated:".$smsmessage->dateCreated."";
            echo "smsMessageSid:".$smsmessage->smsMessageSid."";
            //下面可以自己添加成功处理逻辑*/

            echo $num;
        }
    }

    /**
     * 前台注销
     *
     */
    public function cancellation ()
    {
        session(null,'think');
        Session::delete('web');
        Session::delete('cid');
        cookie('tel', null);
        return view('logining');
    }


    /**
     * 手机端课程分类列表
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function md_show_course ($id)
    {
        // 查询类名
        $data = Db::name('category')
            ->field('catename')
            ->where('id', $id)
            ->find();
        $name = $data['catename'];
        $cid = $id;

        $res = $this->find_cate($id);
        //        var_dump($res); die;
        return view('class/mob-course',['data'=>$res, 'name'=>$name, 'cid'=>$cid]);
    }


    /**
     * 前台课程分类页
     * @param $id "课程id"
     * @return \think\response\View
     */
    
    public function find_cate($id,$limit=10000)
    {
        $path = '0,'.$id;
        // dump($path);die;
        $two = Db::name('category')->where('path','like',$path.'%')->field('id')->select();
        // dump($two);die;
        $res = $id;
        foreach($two as $k=>$v){
            $res .= ','.$v['id'];
        }
        // dump($res);die;
        $course = Db::name('course')->alias('c')
            ->field('c.name,c.id,c.description,c.price,p.address')
            ->join('coursepicture p','p.courseid=c.id')
            ->where('c.categoryid','in',$res)
            ->where('c.display','1')
            ->where('p.cover','1')
            ->limit($limit)
            ->buildsql();
            $res = Db::query($course);

        return $res;
    }


    public function show_course($id)
    {
        $res = $this->find_cate($id);
        
        return view('class/course',['course'=>$res]);
    }


    public function search_course()
    {
        $data = input('post.');
        // dump($data);die;
        $data['index_none_header_sysc'] = strip_tags($data['index_none_header_sysc']);
        // dump($data['index_none_header_sysc']);die;
        $course = Db::name('course')
            ->alias('c')
            ->field('c.name,c.id,c.description,c.price,p.address')
            ->join('coursepicture p','p.courseid=c.id')
            ->where('c.name','like','%'.$data['index_none_header_sysc'].'%')
            ->where('p.cover','1')
            ->where('c.display','1')
            ->select();
        // dump($course);die;
        header("Cache-control: private");

        return view('class/course',['course'=>$course,'sousuo'=>$data['index_none_header_sysc']]);
    }

    public function xiao_cate()
    {
        $id = input('post.')['id'];

        $c_two = Db::name('category')->where('pid',$id)->field('catename,id')->select();
       
       if(empty($c_two)){
            return false;
       }else{
            foreach($c_two as $k=>$v){
                $c_two[$k]['son'] = Db::name('category')->where('pid',$v['id'])->field('catename,id')->select();

                // $res[$v['id']] = $v['catename'];
            }
            // dump($c_two);die;
            return $c_two;
        }
    }


    /**
     * 前台课程详情
     * @param $id "课程id"
     * @return \think\response\View
     */
    public function detail_course($id)
    {

        // 查看是否已加入收藏
        $couse = Db::name('ilike')
            ->where('uid', session('web.uid'))
            ->where('categoryid', $id)
            ->find();

        //带着id去找该课程的信息
        $course = Db::name('course')->alias('c')
            ->field('c.name,c.id,c.description,c.price,p.address')
            ->join('coursepicture p','p.courseid=c.id')
            ->where('c.id',$id)
            ->where('c.display','1')

            ->where('p.cover', '1')
            ->buildsql();
            $res = Db::query($course);

            if(empty($res)){
                $this->error('暂无数据...');
            }

         // 查询课程详情图片
        $pictures = Db::name('coursepicture')
            ->field('address')
            ->where('courseid', $id)
            ->where('cover', '0')
            ->select();

        return view('class/detail',['course'=>$res, 'imgs' => $pictures, 'shifou' => $couse]);
    }

    //qq登录
    public function mylogin()
    {
        $code = input('get.');
        //qqlogin()为自定义函数 传入qq返回的code参数
        $data = qqlogin($code['code']);
        //数据库查询是否有openid  如果有直接登入  没有就写入数据库
        $qqlog = Db::name('web_users')->where('openid',$data['openid'])->find();
        if ($qqlog){
        session('web', ['uid' => $qqlog['id'], 'tel' => $qqlog['tel'], 'nickname' => $qqlog['nickname'],'face'=>$qqlog['face']]);
        $this->redirect('/');
        }else{
            $data['tel'] = rand(100000,999999);
            $data['pass'] = time();
            $res = Db::name('web_users')->insert($data);

            $qquser = Db::name('web_users')->where('openid',$data['openid'])->find();
            session('web', ['uid' => $qquser['id'], 'tel' => $qquser['tel'], 'nickname' => $qquser['nickname'],'face'=>$qquser['face']]);
            $this->redirect('/');
        }

       


    }
    //验证码注册
     public function fsms()
    {
        // 6位验证码  random(100000, 999999)
        // return (333333);die;
        $data = input('post.');

        $tel = $data['tel'];
        $num = rand(100000, 999999);

        session('mtel',$tel,'think');
        session('smscode',$num,'think');
        // dump($num);die;
    // return $tel;
        $res = sendTemplateSMS($tel,array($num,10),"1");
        return $res;
        
        
       // dump($res);die;
    }


}
